package com.business.action.admin.system;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.rose.boot.BootStrap;
import net.sf.rose.file.scan.ClassFilter;
import net.sf.rose.file.scan.PackageScan;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.task.RoseTask;
import net.sf.rose.task.RoseTaskBean;
import net.sf.rose.task.RoseTaskThread;
import net.sf.rose.task.Task;

@Controller
@RequestMapping("/admin/task")
public class TaskAction {

	/**
	 * 获取系统内所有的定时任务类
	 */
	@ResponseBody
	@RequestMapping("/getAllTaskClassName.do")
	public PageBean getAllTaskClassName() {
		PageBean page = new PageBean();
		PackageScan ps = new PackageScan();
		ClassFilter cf = new ClassFilter() {
			@Override
			public boolean accept(Class<?> clazz) {
				// 系统内所有的任务类
				if (RoseTask.class.isAssignableFrom(clazz)) {
					// 必须不是抽象类和接口
					if (!Modifier.isAbstract(clazz.getModifiers()) && !Modifier.isInterface(clazz.getModifiers())) {
						return true;
					}
				}
				return false;
			}
		};
		List<RoseTaskBean> list = new ArrayList<>();
		for (Class<?> clazz : ps.scanPackage("com.business,net.sf.rose", cf)) {
			RoseTaskBean bean = new RoseTaskBean();
			bean.setClassName(clazz.getName());
			Task task = clazz.getAnnotation(Task.class);
			if (task != null) {
				bean.setTaskName(task.value());
			}
			list.add(bean);
		}
		page.setData(list);
		return page;
	}

	@ResponseBody
	@RequestMapping("/save.do")
	public PageBean save(Service service, RoseTaskBean bean) {
		PageBean page = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.createSaveSql(bean);
		if (dao.update() == 0) {
			page.setSuccess(false);
			page.setMessage("保存失败！");
			return page;
		}
		if (bean.getNeedStart() == 1) {
			BootStrap.startTask(bean);
		} else {
			BootStrap.stopTask(bean);
		}
		return page;
	}

	@ResponseBody
	@RequestMapping("/delete.do")
	public PageBean delete(Service service, String taskID) {
		PageBean page = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.createDeleteSql(RoseTaskBean.class, taskID);
		if (dao.update() == 0) {
			page.setSuccess(false);
			page.setMessage("删除失败！");
			return page;
		}
		RoseTaskBean bean = new RoseTaskBean();
		bean.setTaskID(taskID);
		BootStrap.stopTask(bean);
		return page;
	}

	/**
	 * 临时执行一次任务
	 */
	@ResponseBody
	@RequestMapping("/startTask.do")
	public PageBean startTask(RoseTaskBean bean) {
		PageBean page = new PageBean();
		RoseTaskThread thread = new RoseTaskThread();
		bean.setExcuteDateTime(null);
		thread.start(bean);
		return page;
	}
}
